const WrongQuestion = require('../models/WrongQuestion');
const User = require('../models/User');
const Question = require('../models/Question');
const QuestionCategory = require('../models/QuestionCategory');
const QuestionComment = require('../models/QuestionComment');
const { Op } = require('sequelize');
const sequelize = require('../db/db');
const { sendResponse, sendListResponse } = require('../utils/response');
const { getTimestamp, getTwoDigits, formatObject } = require('../utils/common');

/**
 * 新增错题记录
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 * @param {Object} req.body - 请求体
 * @param {string} req.body.userId - 用户ID
 * @param {string} req.body.questionId - 题目ID
 */
const addWrongQuestion = async (req, res) => {
  try {
    const { userId, questionId } = req.body;

    // 检查参数是否存在
    if (!userId || !questionId) {
      return sendResponse(res, 500, '参数错误: 用户ID和题目ID不能为空');
    }

    // 查找是否已存在该错题记录
    const existingRecord = await WrongQuestion.findOne({
      where: {
        user_id: userId,
        question_id: questionId
      }
    });

    if (existingRecord) {
      // 如果已存在，更新错误次数和最后错误时间
      await existingRecord.update({
        error_count: existingRecord.error_count + 1,
        last_wrong_time: new Date()
      });
      sendResponse(res, 200, '错题记录更新成功');
    } else {
      // 如果不存在，创建新记录
      const wrongQuestionId = "190" + getTimestamp() + getTwoDigits();
      await WrongQuestion.create({
        id: wrongQuestionId,
        user_id: userId,
        question_id: questionId,
        error_count: 1,
        last_wrong_time: new Date()
      });
      sendResponse(res, 200, '错题记录创建成功');
    }
  } catch (error) {
    console.error('添加错题记录失败:', error);
    sendResponse(res, 500, '添加错题记录失败', error.message);
  }
};

/**
 * 删除错题记录
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 * @param {Object} req.query - 查询参数
 * @param {string} [req.query.id] - 错题记录ID (方式1)
 * @param {string} [req.query.userId] - 用户ID (方式2)
 * @param {string} [req.query.questionId] - 题目ID (方式2)
 */
const deleteWrongQuestion = async (req, res) => {
  try {
    const { id, userId, questionId } = req.query;

    let whereCondition = {};

    // 方式1: 通过错题记录ID删除
    if (id) {
      whereCondition = { id };
    }
    // 方式2: 通过用户ID和题目ID组合删除
    else if (userId && questionId) {
      whereCondition = {
        user_id: userId,
        question_id: questionId
      };
    }
    // 参数不足
    else {
      return sendResponse(res, 500, '参数错误: 需要提供错题ID或用户ID和题目ID的组合');
    }

    const result = await WrongQuestion.destroy({
      where: whereCondition
    });

    if (result > 0) {
      sendResponse(res, 200, '错题记录删除成功');
    } else {
      sendResponse(res, 404, '错题记录不存在');
    }
  } catch (error) {
    console.error('删除错题记录失败:', error);
    sendResponse(res, 500, '删除错题记录失败', error.message);
  }
};

/**
 * 获取用户的错题列表
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 * @param {Object} req.query - 查询参数
 * @param {string} req.query.userId - 用户ID
 * @param {number} [req.query.page=1] - 页码
 * @param {number} [req.query.pageSize=10] - 每页条数
 * @param {string} [req.query.difficulty] - 难度
 */
const getUserWrongQuestions = async (req, res) => {
  try {
    const { userId, page = 1, pageSize = 10, difficulty } = req.query;

    // 检查参数是否存在
    if (!userId) {
      return sendResponse(res, 500, '参数错误: 用户ID不能为空');
    }
    // 计算偏移量
    const offset = (page - 1) * pageSize;

    // 构建查询条件
    const whereCondition = { user_id: userId };
    const questionWhereCondition = {};

    // 如果传入了难度参数，添加到题目查询条件中
    if (difficulty) {
      questionWhereCondition.difficulty = difficulty;
    }

    // 查询错题记录
    const { count, rows } = await WrongQuestion.findAndCountAll({
      where: whereCondition,
      include: [
        {
          model: Question,
          as: 'question',
          attributes: [
            'id', 'content', 'options', 'difficulty', 'category_id',
            'user_rated_difficulty', 'user_rated_quality', 'rating_count'
          ],
          where: questionWhereCondition,
          include: [
            {
              model: QuestionCategory,
              as: 'category',
              attributes: ['name']
            }
          ]
        }
      ],
      order: [['last_wrong_time', 'DESC']],
      limit: parseInt(pageSize),
      offset: parseInt(offset)
    });

    // 格式化返回数据
    const formattedList = rows.map(record => {
      const questionData = record.question.toJSON();

      return formatObject({
        id: record.id,
        questionId: record.question_id,
        errorCount: record.error_count,
        lastWrongTime: record.last_wrong_time,
        question: formatObject({
          ...questionData,
          categoryName: questionData.category ? questionData.category.name : '',
          userRatedDifficulty: parseFloat(questionData.user_rated_difficulty) || 0,
          userRatedQuality: parseFloat(questionData.user_rated_quality) || 0
        })
      });
    });

    sendListResponse(res, 200, '获取错题列表成功', formattedList, count);
  } catch (error) {
    console.error('获取错题列表失败:', error);
    sendResponse(res, 500, '获取错题列表失败', error.message);
  }
};

/**
 * 获取题目的错误统计
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 * @param {Object} req.params - 路径参数
 * @param {string} req.params.questionId - 题目ID
 */
const getQuestionWrongStats = async (req, res) => {
  try {
    const { questionId } = req.params;

    // 检查参数是否存在
    if (!questionId) {
      return sendResponse(res, 500, '参数错误: 题目ID不能为空');
    }

    // 获取错题人数
    const wrongCount = await WrongQuestion.count({
      where: { question_id: questionId }
    });

    // 获取错题用户列表
    const wrongRecords = await WrongQuestion.findAll({
      where: { question_id: questionId },
      include: [
        {
          model: User,
          as: 'user',
          attributes: ['user_id', 'nickname']
        }
      ],
      order: [['error_count', 'DESC']]
    });

    // 格式化返回数据
    const formattedRecords = wrongRecords.map(record => formatObject({
      userId: record.user.user_id,
      nickname: record.user.nickname,
      errorCount: record.error_count,
      lastWrongTime: record.last_wrong_time
    }));

    sendResponse(res, 200, '获取题目错误统计成功', formatObject({
      wrongCount,
      wrongUsers: formattedRecords
    }));
  } catch (error) {
    console.error('获取题目错误统计失败:', error);
    sendResponse(res, 500, '获取题目错误统计失败', error.message);
  }
};

/**
 * 获取错题列表
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 * @param {Object} req.query - 查询参数
 * @param {number} [req.query.page=1] - 页码
 * @param {number} [req.query.pageSize=10] - 每页条数
 * @param {string} [req.query.content] - 题目内容搜索关键词
 * @param {string} [req.query.difficulty] - 难度过滤
 * @param {string} [req.query.categoryId] - 分类ID过滤
 */
const getWrongQuestionList = async (req, res) => {
  try {
    const { page = 1, pageSize = 10, content, difficulty, categoryId } = req.query;
    
    // 计算分页偏移量
    const offset = (page - 1) * pageSize;
    const limit = parseInt(pageSize);
    
    // 构建题目查询条件
    const questionWhere = {
      is_delete: 0
    };
    
    if (content) {
      questionWhere.content = {
        [Op.like]: `%${content}%`
      };
    }
    
    if (difficulty) {
      questionWhere.difficulty = difficulty;
    }
    
    if (categoryId) {
      questionWhere.category_id = categoryId;
    }
    
    // 查询错题列表，按照错题次数降序排序
    const wrongCountQuery = await WrongQuestion.findAll({
      attributes: [
        'question_id',
        [sequelize.fn('SUM', sequelize.col('error_count')), 'total_error_count']
      ],
      group: ['question_id'],
      order: [[sequelize.literal('total_error_count'), 'DESC']],
      raw: true
    });
    
    // 如果没有错题记录，直接返回空列表
    if (wrongCountQuery.length === 0) {
      return sendListResponse(res, 200, '查询成功', [], 0);
    }
    
    // 获取所有错题ID和错题次数
    const wrongQuestionMap = {};
    wrongCountQuery.forEach(item => {
      wrongQuestionMap[item.question_id] = parseInt(item.total_error_count);
    });
    
    // 分页获取题目ID列表
    const questionIds = wrongCountQuery
      .map(item => item.question_id)
      .slice(offset, offset + limit);
    
    // 查询题目详细信息
    const questions = await Question.findAll({
      where: {
        id: {
          [Op.in]: questionIds
        },
        ...questionWhere
      },
      attributes: [
        'id', 'content', 'options', 'correct_key', 'difficulty', 
        'category_id', 'status', 'user_id', 'create_time',
        'user_rated_difficulty', 'user_rated_quality', 'rating_count'
      ],
      include: [
        {
          model: QuestionCategory,
          as: 'category',
          attributes: ['id', 'name'],
          required: false
        },
        {
          model: User,
          as: 'creator',
          attributes: ['user_id', 'nickname'],
          required: false
        }
      ]
    });
    
    // 获取每个题目的评论数量
    const commentCounts = await QuestionComment.findAll({
      attributes: [
        'question_id',
        [sequelize.fn('COUNT', sequelize.col('id')), 'comment_count']
      ],
      where: {
        question_id: {
          [Op.in]: questionIds
        }
      },
      group: ['question_id'],
      raw: true
    });
    
    // 将评论数量映射为对象
    const commentMap = {};
    commentCounts.forEach(item => {
      commentMap[item.question_id] = parseInt(item.comment_count);
    });
    
    // 格式化结果并按错题次数降序排序
    const formattedResults = questions.map(question => {
      const questionData = formatObject(question.toJSON());
      return {
        ...questionData,
        errorCount: wrongQuestionMap[question.id] || 0,
        commentCount: commentMap[question.id] || 0,
        userRatedDifficulty: parseFloat(questionData.userRatedDifficulty) || 0,
        userRatedQuality: parseFloat(questionData.userRatedQuality) || 0
      };
    }).sort((a, b) => b.errorCount - a.errorCount);
    
    // 查询符合条件的总记录数
    const totalCount = await Question.count({
      where: {
        id: {
          [Op.in]: wrongCountQuery.map(item => item.question_id)
        },
        ...questionWhere
      }
    });
    
    sendListResponse(res, 200, '查询成功', formattedResults, totalCount);
  } catch (error) {
    console.error('查询错题列表失败:', error);
    sendResponse(res, 500, '查询错题列表失败', error.message);
  }
};

module.exports = {
  addWrongQuestion,
  deleteWrongQuestion,
  getUserWrongQuestions,
  getQuestionWrongStats,
  getWrongQuestionList
}; 